package org.example.servlet;

import org.example.service.OrderService;
import org.example.service.OrderServiceImpl;
import org.example.model.Order;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;
import java.util.Date;

@WebServlet("/payment/process")
public class PaymentServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            // 获取用户ID
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(result.toString());
                return;
            }
            
            // 读取请求体
            String requestBody = request.getReader().lines().collect(Collectors.joining());
            JSONObject paymentData = new JSONObject(requestBody);
            
            // 创建订单
            Order order = new Order();
            order.setOrderNumber(paymentData.getString("orderNumber"));
            order.setUserId(userId);
            order.setTotalAmount(paymentData.getDouble("amount"));
            order.setOrderStatus("待发货");
            // 设置支付时间
            order.setPaymentTime(new Date());
            
            // 保存订单
            boolean success = orderService.createOrder(order, paymentData.getJSONArray("items"));
            
            result.put("success", success);
            if (!success) {
                result.put("message", "创建订单失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
} 